package com.video.zlc.audioplayer.ui;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.video.zlc.audioplayer.R;
import com.video.zlc.audioplayer.adapter.RecordAdapter;
import com.video.zlc.audioplayer.business.AudioBusiness;
import com.video.zlc.audioplayer.info.RecordVoiceInfo;
import com.video.zlc.audioplayer.utils.CircleProgressBar;
import com.video.zlc.audioplayer.utils.DensityUtil;
import com.video.zlc.audioplayer.utils.LogUtil;
import com.video.zlc.audioplayer.business.MediaBusiness;

import java.util.ArrayList;
import java.util.List;

/**
 * 问题详情页
 * Created by zlc on 2016/6/11.
 */
public class RecordVoiceActivity extends BaseActivity implements View.OnClickListener,AudioManager.OnAudioFocusChangeListener,ListView.OnItemClickListener{

    private ImageView im_fanhui;
    private TextView title;
    private TextView id_tv_answer;
    private ImageView id_bt_start_luyin;
    private CircleProgressBar id_cpb;
    private TextView id_tv_time;
    private String dir;
    private AudioBusiness mAudioManage;
    private boolean isRecording = false;
    private int mTime;
    private LinearLayout id_ll_time;
    private TextView id_tv_second;
    private TextView id_tv_record_zy;
    private int stime;
    private Thread tryListenThread;
    private float progress;    //录的时候进度
    private float listenerProgress;   //听的时候进度
    private String lastVoicePath;

    private TextView id_tv_try_listen;
    private TextView id_tv_restart_record;
    private TextView id_tv_send;
    private ImageView id_iv_voice;
    private AnimationDrawable animationDrawable;
    private ListView id_list_voice;
    private RecordAdapter mAdapter;
    private RecordVoiceInfo recordInfo;
    private Thread recordThread;

    //录音相关的
    private AudioManager am;
    private PowerManager.WakeLock wakeLock;
    private List<RecordVoiceInfo> records = new ArrayList<>();
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    id_tv_record_zy.setText("再次点击停止录制" + "\n");
                    id_cpb.setFirstProgress(progress);
                    if(mTime % 5 ==0) {
                        id_tv_time.setText(mTime / 5 + "");
                        id_tv_second.setText("S");
                    }
                    break;
                case 1:
                    recordFinish();
                    break;
                case 3:
                    id_cpb.setFirstProgress(listenerProgress);
                    if(stime % 5 == 0) {
                        int time = stime / 5 > 60 ? 60 : stime / 5;
                        id_tv_time.setText(time + "");
                        id_tv_second.setText("S");
                    }
                    break;
                case 4:
                    id_tv_try_listen.setText("试听");
                    if(tryListenThread !=null){
                        tryListenThread.interrupt();
                        tryListenThread = null;
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        //不让屏幕黑屏
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My lock");
        wakeLock.setReferenceCounted(false);

        initView();
        initData();
        initListener();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_fenda_detail;
    }

    //初始化控件
    protected void initView() {
        im_fanhui = findView(R.id.id_iv_fanhui);
        title = findView(R.id.id_tv_title);
        id_tv_answer = findView(R.id.id_tv_answer);
        id_tv_time = findView(R.id.id_tv_time);
        id_bt_start_luyin = findView(R.id.id_bt_start_luyin);
        id_cpb = findView(R.id.id_cpb);
        id_ll_time = findView(R.id.id_ll_time);
        id_tv_record_zy = findView(R.id.id_tv_record_zy);
        id_tv_second = findView(R.id.id_tv_second);
        id_list_voice = findView(R.id.id_list_voice);

        id_tv_try_listen = findView(R.id.id_tv_try_listen);
        id_tv_restart_record = findView(R.id.id_tv_restart_record);
        id_tv_send = findView(R.id.id_tv_send);
    }

    //加载数据
    protected void initData() {
        title.setText("问题详情");
        title.setTextSize(18);
        if(Environment.MEDIA_UNMOUNTED.equals(Environment.getExternalStorageState())
                ||!Environment.isExternalStorageRemovable()){
            dir = getExternalCacheDir().getAbsolutePath();
        }else{
            dir = getCacheDir().getAbsolutePath();
        }
        mAudioManage = AudioBusiness.getInstance(dir);
    }

    //点击事件监听
    protected void initListener() {
        //开始录音
        id_bt_start_luyin.setOnClickListener(this);
        //点击暂停
        id_cpb.setOnClickListener(this);
        //点击试听
        id_tv_try_listen.setOnClickListener(this);
        //点击重录
        id_tv_restart_record.setOnClickListener(this);
        //点击发送语音
        id_tv_send.setOnClickListener(this);
        //点击返回
        im_fanhui.setOnClickListener(this);

        id_list_voice.setOnItemClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(wakeLock!=null) {
            wakeLock.acquire();   //请求常亮
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(wakeLock!=null){
            wakeLock.release();   //释放锁
        }
        if(am!=null){
            am.abandonAudioFocus(this);
        }
        if(MediaBusiness.isPlaying()) {
            MediaBusiness.pause();
        }
    }

    /**
     * 试听录音
     */
    private void tryListenVoice() {
        id_cpb.setMaxProgressWidth(0);
        id_cpb.setFirstProgressWidth(2);
        id_cpb.setMaxProgress(mTime / 5);
        id_cpb.setCanDisplayDot(false);
        id_cpb.setFirstProgressColor(ContextCompat.getColor(this,R.color.white));
        String s = id_tv_try_listen.getText().toString();
        if (s.equals("停止")) {
            MediaBusiness.pause();
            id_cpb.setFirstProgress(progress);
            id_tv_time.setText(mTime / 5 +"");
            id_tv_second.setText("S");
            id_tv_try_listen.setText("试听");
            if (tryListenThread != null) {
                tryListenThread.interrupt();
                tryListenThread = null;
            }
        } else if (s.equals("试听")) {
            String voicePath = mAudioManage.getCurrentFilePath();
            LogUtil.e("voicePath",voicePath);
            if(TextUtils.isEmpty(voicePath) || !voicePath.contains(".mp3")){
                Toast.makeText(this,"语音文件不合法",Toast.LENGTH_LONG).show();
                return;
            }
            listenerProgress = 0;
            stime = 0;
            id_cpb.setFirstProgress(0);
            id_tv_time.setText("");
            id_tv_second.setText("");
            id_tv_try_listen.setText("停止");
            MediaBusiness.playSound(this,voicePath, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    LogUtil.e("listenerVoice","试听完成");
                }
            });
            if (tryListenThread == null) {
                tryListenThread = new Thread(listenRunnable);
            }
            if(!tryListenThread.isAlive())
                tryListenThread.start();
        }
    }

    /**
     *录音停止
     */
    private void recordFinish() {

        isRecording = false;
        if(recordThread != null){
            recordThread.interrupt();
            recordThread = null;
        }
        am.abandonAudioFocus(this);
        mAudioManage.stop();
        id_tv_answer.setText("录音完成");
        id_tv_record_zy.setVisibility(View.GONE);
        isShowView(View.VISIBLE,id_tv_try_listen,id_tv_restart_record,id_tv_send);
        setTranslate(id_tv_try_listen, getWindowWidth(),"x");
        setTranslate(id_tv_restart_record, -getWindowWidth(),"x");
        setTranslate(id_tv_send, -DensityUtil.dp2px(this,66),"y");

        recordInfo = new RecordVoiceInfo();
        recordInfo.setTime(mTime / 5);
        recordInfo.setPath(mAudioManage.getCurrentFilePath());
        if(!mAudioManage.getCurrentFilePath().equals(lastVoicePath)){
            records.add(recordInfo);
        }
        lastVoicePath = mAudioManage.getCurrentFilePath();
        LogUtil.e("语音文件路径",mAudioManage.getCurrentFilePath());
    }

    /**
     * 开始录音
     */
    private void startRecord() {

        if(records!=null && records.size() >=5){
            Toast.makeText(this,"最多录制5条语音",Toast.LENGTH_LONG).show();
            return;
        }
        id_cpb.setMaxProgressWidth(0);
        id_cpb.setFirstProgressWidth(2);
        id_cpb.setMaxProgress(60);
        id_cpb.setCanDisplayDot(false);
        id_cpb.setFirstProgressColor(ContextCompat.getColor(this,R.color.white));
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //LogUtil.e("系统音量级别",am.getStreamMaxVolume(AudioManager.STREAM_MUSIC)+"");
        //录音时候把系统音量设置为最大
        am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_PLAY_SOUND);
        int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            am.unregisterMediaButtonEventReceiver(new ComponentName(this,getPackageName()));
            mAudioManage.prepareAudio();
            isRecording = true;
            if(recordThread == null)
                recordThread = new Thread(recordRunnable);
            if(!recordThread.isAlive()){
                recordThread.start();
            }
            id_tv_answer.setText("录音中");
            id_bt_start_luyin.setVisibility(View.GONE);
            isShowView(View.VISIBLE, id_cpb, id_ll_time);
        }
    }

    /**
     * 重新录制音频文件
     */
    private void restartRecord(String from) {
        //删除之前的文件
        if("restart".equals(from)) {
            records.remove(recordInfo);
            mAudioManage.delete();
        }else if("send".equals(from)){
            MediaBusiness.stop();
            mAudioManage.release();
        }
        id_tv_answer.setText("语音回答");
        String s = "点击开始语音录制"+"\n"+"最多可录制60s";
        id_tv_record_zy.setText(s);
        id_tv_try_listen.setText("试听");
        id_tv_time.setText("");
        id_tv_second.setText("");
        mTime = 0;
        isShowView(View.VISIBLE, id_tv_record_zy, id_bt_start_luyin);
        isShowView(View.GONE, id_cpb,id_tv_try_listen,id_tv_restart_record,id_tv_send, id_ll_time);
        id_tv_time.setText("");
        id_tv_second.setText("");
        if(tryListenThread !=null){
            tryListenThread.interrupt();
            tryListenThread = null;
        }
        id_cpb.setFirstProgress(0);
        progress = 0;
        listenerProgress = 0;
    }

    //是否显示控件
    public void isShowView(int visable,View...views){
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(visable);
        }
    }

    /**
     *录音线程
     */
    private final Runnable recordRunnable = new Runnable() {
        @Override
        public void run() {
            while (isRecording) {
                try {
                    SystemClock.sleep(200);
                    progress += 0.2;
                    ++mTime;
                    int what = mTime / 5 <= 60 ? 0 : 1;
                    mHandler.sendEmptyMessage(what);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.e("recordRunnable",e.getMessage());
                }
            }
        }
    };

    /**
     * 录制完成的动画
     */
    public void setTranslate(View v, int width, String type){
        ObjectAnimator anim2  = type.equals("x") ? ObjectAnimator.ofFloat(v, "translationX",
                width, 0) : ObjectAnimator.ofFloat(v, "translationY", width, 0);
        ObjectAnimator anim3 = ObjectAnimator.ofFloat(v,"scaleX",0f,1f);
        ObjectAnimator anim4 = ObjectAnimator.ofFloat(v,"scaleY",0f,1f);
        AnimatorSet animSet = new AnimatorSet();
        animSet.setDuration(500);
        animSet.setInterpolator(new LinearInterpolator());
        animSet.play(anim2).with(anim3).with(anim4);
        animSet.start();
    }

    /**
     * 获取平移宽度
     */
    public int getWindowWidth(){
        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        width = width / 2  - DensityUtil.dp2px(this,32);
        return width;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.id_bt_start_luyin:
                Acp.getInstance(this).request(new AcpOptions.Builder()
                                .setPermissions(Manifest.permission.RECORD_AUDIO)
                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                                startRecord();
                            }
                            @Override
                            public void onDenied(List<String> permissions) {
                                LogUtil.e("msg","设备权限没拿到");
                            }
                        });
                break;
            case R.id.id_cpb:
                if(id_tv_answer.getText().toString().equals("录音中")) {
                    recordFinish();
                }
                break;
            case R.id.id_tv_try_listen:   //试听
                 tryListenVoice();
                break;
            case R.id.id_tv_restart_record:    //重录
                showDialog();
                break;
            case R.id.id_tv_send:    //发送语音
                sendVoice();
                break;
            case R.id.id_iv_fanhui:
                finish();
                break;
        }
    }

    private int lastPos = -1;
    //播放语音
    private void playVoice(final int position, String from) {

        LogUtil.e("playVoice position",position+"");
        if(position >= records.size()) {
            LogUtil.e("playVoice","全部播放完了");
            stopAnimation();
            MediaBusiness.reset();
            return;
        }

        String voicePath = records.get(position).getPath();
        LogUtil.e("playVoice",voicePath);
        if(TextUtils.isEmpty(voicePath) || !voicePath.contains(".mp3")){
            Toast.makeText(this,"语音文件不合法",Toast.LENGTH_LONG).show();
            return;
        }

        if(lastPos != position && "itemClick".equals(from)){
            stopAnimation();
            MediaBusiness.reset();
        }
        lastPos = position;

        int pos = position - id_list_voice.getFirstVisiblePosition();
        View view = id_list_voice.getChildAt(pos);
        id_iv_voice = (ImageView) view.findViewById(R.id.id_iv_voice);
        LogUtil.e("playVoice position",pos+"");

        if(MediaBusiness.isPlaying()){
            MediaBusiness.pause();
            stopAnimation();
        }else if(MediaBusiness.isPause()){
            startAnimation();
            MediaBusiness.resume();
        }else{
            startAnimation();
            MediaBusiness.playSound(this,voicePath, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    //播放完停止动画 重置MediaManager
                    stopAnimation();
                    MediaBusiness.reset();

                    playVoice(position + 1, "loop");
                }
            });
        }
    }

    private void startAnimation(){
        if(id_iv_voice == null)
            return;
        id_iv_voice.setBackgroundResource(R.drawable.animation_voice);
        animationDrawable = (AnimationDrawable) id_iv_voice.getBackground();
        if (animationDrawable != null && !animationDrawable.isRunning()) {
            animationDrawable.start();
        }
    }

    private void stopAnimation(){
        if(id_iv_voice == null)
            return;
        if (animationDrawable != null && animationDrawable.isRunning()) {
            animationDrawable.stop();
            id_iv_voice.setBackgroundResource(R.drawable.voice_listen);
        }
    }

    private void sendVoice() {

        restartRecord("send");

        if(mAdapter == null)
            id_list_voice.setAdapter(mAdapter = new RecordAdapter(this,records));
        else
            mAdapter.notifyDataSetChanged();
    }

    //重新录制弹出对话框确认
    private void showDialog() {
        final AlertDialog.Builder dialog =
                new AlertDialog.Builder(this);
        dialog.setTitle("提醒?");
        dialog.setMessage("你确定要重录吗?");
        dialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        restartRecord("restart");
                        dialog.dismiss();
                    }
                });
        dialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        // 显示
        dialog.show();
    }

    @Override
    public void onAudioFocusChange(int focusChange) {
       if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
            am.abandonAudioFocus(this);
       }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        //id_iv_voice = (ImageView) view.findViewById(R.id.id_iv_voice);
        playVoice(position,"itemClick");
    }

    private final Runnable listenRunnable = new Runnable() {
        @Override
        public void run() {
            while (MediaBusiness.isPlaying()){
                try {
                    SystemClock.sleep(200);
                    listenerProgress += 0.2;
                    ++stime;
                    int what = stime <= mTime ? 3 : 4;
                    mHandler.sendEmptyMessage(what);
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtil.e("ListenerRunnable",e.getMessage());
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(wakeLock!=null){
            wakeLock.release();
            wakeLock = null;
        }
        MediaBusiness.release();
        if(mAudioManage != null)
            mAudioManage.release();
    }

}
